﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.ESB.Adapter;
using Microsoft.Practices.ESB.Exception.Management;
using Microsoft.Practices.ESB.Itinerary;
using Microsoft.Practices.ESB.Itinerary.Services;
using Microsoft.Practices.ESB.Resolver;
using Microsoft.BizTalk.Component.Interop;
using Microsoft.BizTalk.Message.Interop;
using System.Reflection;

namespace BizTalk.ESB.Extensions.MessagingServices
{
    public class WcfActionRouting : IMessagingService
    {
        IBaseMessage IMessagingService.Execute(IPipelineContext context, IBaseMessage msg, string resolverString, IItineraryStep step)
        {
            if (context == null)
                throw new ArgumentNullException("context");
            if (msg == null)
                throw new ArgumentNullException("msg");
            if (string.IsNullOrEmpty(resolverString))
                throw new ArgumentException("Resolver must be provided", "resolverString");
            try
            {
                ResolverInfo info = ResolverMgr.GetResolverInfo(ResolutionType.Endpoint, resolverString);
                if (!info.Success)
                    throw new RoutingException("Invalid Resolver", resolverString);

                // Resolve configuration for routing.
                Dictionary<string, string> resolverDictionary = ResolverMgr.Resolve(info, msg, context);

                if (string.IsNullOrEmpty(resolverDictionary["Resolver.Action"]))
                {
                    throw new RoutingException("Action not provided in Resolver", resolverString);
                }

                //AdapterMgr.SetEndpoint(resolverDictionary, msg.Context);
                msg.Context.Promote("Action", @"http://schemas.microsoft.com/BizTalk/2006/01/Adapters/WCF-properties", resolverDictionary["Resolver.Action"]);

                return msg;
            }
            catch (System.Exception ex)
            {
                EventLogger.Write(MethodInfo.GetCurrentMethod(), ex);
                throw;
            }    
        }

        string IMessagingService.Name
        {
            get { return "BizTalk.Core.Itinerary.MessagingServices.WcfActionRouting"; }
        }

        bool IMessagingService.ShouldAdvanceStep(IItineraryStep step, IBaseMessage msg)
        {
            return true;
        }

        bool IMessagingService.SupportsDisassemble
        {
            get { return false; }
        }
    }
}
